package com.lik888.web1.Interceptor;


import com.lik888.web1.constants.UserContext;
import com.lik888.web1.utils.JwtTool;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;




@Component
public class LoginInterceptor  implements HandlerInterceptor {
    @Autowired
    private JwtTool jwtTool;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.判断是否登录
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            String auth = request.getHeader("Authorization"); // 或 "authorization"
            if (auth != null && !auth.isEmpty()) {
                // 兼容 Bearer 前缀（大小写不敏感）
                if (auth.toLowerCase().startsWith("bearer ")) {
                    token = auth.substring(7).trim();
                } else {
                    token = auth.trim();
                }
            }
        }
        if (token == null || token.isEmpty()) {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(401);
            response.getWriter().write("未登录");
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }

        Long userId = jwtTool.parseToken(token);
        if (userId == null) {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(401);
            response.getWriter().write("token解析失败");
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        UserContext.setUser(userId);
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
